package cn.drh.charging.order.websocket;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName WebSocketServer
 * @Description TODO
 * @Author renhong~Deng
 * @Date 2025/6/10 21:41
 * @Version 1.0
 */

@Slf4j
@Component
@ServerEndpoint("/ws/server/{userId}")
public class WebSocketServer {
    public static ConcurrentHashMap<Integer,Session> sessions = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法 类似与mqtt connectComplete
     *
     * @param session 会话状态
     * @param userId  用户id
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Integer userId) {
        log.info("onOpen");
        log.debug("用户{}连接成功{}", userId, session);
        sessions.put(userId, session);
    }

    /**
     * session 断开连接调用的方法
     * @param session 会话状态
     * @param userId 用户id
     * @throws IOException 抛出异常
     */
    @OnClose
    public void onClose(Session session, @PathParam("userId") Integer userId) throws IOException {
        log.debug("用户退出{}连接断开", userId);
        sessions.remove(userId);
    }

    @OnError
    public void onError(Session session, @PathParam("userId") Integer userId, Throwable throwable) throws IOException {
        log.error("用户{}连接异常", userId);
        session.close();
    }

    /**
     *
     * @param session
     * @param message
     * @throws IOException
     */
    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        log.debug("用户{}发送消息:{}",session, message);
    }


    public void sendMessage(Integer userId, String message) {
        Session session = sessions.get(userId);
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else {
            log.error("用户{}下线了，发送消息失败", userId);
        }
    }
}
